package com.example.demo.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entify.Power;
import com.example.demo.entify.User;
import com.example.demo.result.Result;
import com.example.demo.result.ResultFactory;
import com.example.demo.service.UserService;
import com.example.demo.service.powerService;

@RestController
@CrossOrigin
@RequestMapping("/power")
public class powerController {
	@Autowired
	private powerService powerService;
	
	@Autowired
	private UserService userService;
	
	
	@GetMapping("/findAllpowers")
	public Result findAllpowers(){
		Map<String, Object> map = new HashMap<>();
			List<String> list =new ArrayList<>();
		List<Power> allPowers =powerService.Allpower();
			
		map.put("allPowers",allPowers);
		for (Power power : allPowers) {
			list.add(power.getName());
		}
		map.put("list",list);
		return  ResultFactory.buildSuccessFactory(map);
	}
	
	@GetMapping("/selectOne")	
	public Result selectOne(@RequestParam Map<String,Object> params) {
		
		User userpower = userService.userPower(params);
		List<String> list = new ArrayList<String>();
		
		String i = userpower.getPowername();
		System.out.println(i);
		
		if (i!=null) {
			list.addAll(Arrays.asList(i.trim().split(",")));
		}
		
		return ResultFactory.buildSuccessFactory(list);
		
	}
	@PostMapping("/updatePower")
	public Result updatePower(@RequestBody Map<String, Object> params) {
			User user = new User();
		  	String arrs= "";
	        List<String> list = (List<String>) params.get("list");
	        for(String arr:list){
	            arrs =arrs+arr.trim()+",";
	        }       
	        if(!list.isEmpty()){
	            arrs = arrs.substring(0,arrs.length()-1);
	        }	        
	        user.setUsername((String)params.get("username"));
	        user.setPowername(arrs);
	       int i = powerService.updatepower(user);
	 
		return i>0 ? ResultFactory.buildSuccessFactory(list) : ResultFactory.buildFailFactory("失败");
	}
	
	

}
